package com.campus.counseling.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.counseling.model.common.Result;
import com.campus.counseling.model.common.exception.ServiceException;
import com.campus.counseling.entity.SysUser;
import com.campus.counseling.model.dto.UserDTO;
import com.campus.counseling.model.dto.ProfileUpdateDTO;
import com.campus.counseling.model.dto.PasswordUpdateDTO;
import com.campus.counseling.model.dto.ResetPasswordDTO;
import com.campus.counseling.model.query.UserQuery;
import com.campus.counseling.model.vo.UserVO;
import com.campus.counseling.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final SysUserService userService;

    @ApiOperation("获取用户列表")
    @GetMapping("/list")
    @PreAuthorize("hasRole('admin') or hasRole('superadmin')")
    public Result<Page<UserVO>> list(UserQuery query) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        log.info("当前用户: {}", auth.getName());
        log.info("当前用户角色: {}", auth.getAuthorities());
        log.info("当前用户是否已认证: {}", auth.isAuthenticated());
        
        // 添加参数校验
        if (query.getPageNum() == null || query.getPageNum() < 1) {
            query.setPageNum(1);
        }
        if (query.getPageSize() == null || query.getPageSize() < 1) {
            query.setPageSize(10);
        }
        
        Page<UserVO> page = userService.getUserPage(query);
        log.info("查询结果: pageNum={}, pageSize={}, total={}, records={}",
            page.getCurrent(), page.getSize(), page.getTotal(), page.getRecords().size());
        
        return Result.success(page);
    }

    @ApiOperation("添加用户")
    @PostMapping
    @PreAuthorize("hasRole('admin') or hasRole('superadmin')")
    public Result<Void> add(@Validated @RequestBody UserDTO userDTO) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        log.info("当前用户: {}", auth.getName());
        log.info("当前用户角色: {}", auth.getAuthorities());
        
        // 只有超级管理员可以创建超级管理员账号
        boolean isSuperAdmin = auth.getAuthorities().stream()
            .anyMatch(a -> a.getAuthority().equals("ROLE_superadmin"));
        
        if (!isSuperAdmin && "superadmin".equals(userDTO.getRole())) {
            throw new ServiceException("只有超级管理员可以创建超级管理员账号");
        }
        
        userService.addUser(userDTO);
        return Result.success();
    }

    @ApiOperation("更新用户")
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('admin') or hasRole('superadmin')")
    public Result<Void> update(@PathVariable Long id, @Validated @RequestBody UserDTO userDTO) {
        // 如果是管理员，不允许修改超级管理员
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_superadmin"))) {
            SysUser targetUser = userService.getById(id);
            if (targetUser != null && "superadmin".equals(targetUser.getRole())) {
                throw new ServiceException("无权修改超级管理员信息");
            }
        }
        userService.updateUser(id, userDTO);
        return Result.success();
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('admin') or hasRole('superadmin')")
    public Result<Void> delete(@PathVariable Long id) {
        // 如果是管理员，不允许删除超级管理员
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_SUPERADMIN"))) {
            SysUser targetUser = userService.getById(id);
            if (targetUser != null && "superadmin".equals(targetUser.getRole())) {
                throw new ServiceException("无权删除超级管理员");
            }
        }
        userService.deleteUser(id);
        return Result.success();
    }

    @PutMapping("/profile")
    @ApiOperation("更新个人信息")
    public Result<Void> updateProfile(@Validated @RequestBody ProfileUpdateDTO profileDTO) {
        // 获取当前登录用户
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        
        // 获取用户ID
        SysUser currentUser = userService.getByUsername(username);
        if (currentUser == null) {
            throw new ServiceException("用户不存在");
        }
        
        // 如果修改了用户名，检查是否与其他用户冲突
        if (StringUtils.hasText(profileDTO.getUsername()) 
            && !profileDTO.getUsername().equals(currentUser.getUsername())) {
            SysUser existUser = userService.getByUsername(profileDTO.getUsername());
            if (existUser != null) {
                throw new ServiceException("用户名已存在");
            }
        }
        
        // 更新用户信息
        userService.updateProfile(currentUser.getId(), profileDTO);
        return Result.success();
    }

    @PutMapping("/password")
    @ApiOperation("修改密码")
    public Result<Void> changePassword(@RequestBody @Validated PasswordUpdateDTO passwordDTO) {
        try {
            // 获取当前登录用户
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String username = auth.getName();
            log.info("修改密码请求: username={}", username);
            
            // 获取用户ID
            SysUser currentUser = userService.getByUsername(username);
            if (currentUser == null) {
                log.error("用户不存在: username={}", username);
                throw new ServiceException("用户不存在");
            }
            
            // 修改密码
            userService.changePassword(currentUser.getId(), passwordDTO.getOldPassword(), passwordDTO.getNewPassword());
            return Result.success();
        } catch (ServiceException e) {
            log.warn("修改密码失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("修改密码异常", e);
            return Result.error("修改密码失败，请稍后重试");
        }
    }

    @PostMapping("/{id}/reset-password")
    @Operation(summary = "重置用户密码")
    public Result<Void> resetPassword(
        @PathVariable Long id,
        @RequestBody ResetPasswordDTO request) {
        userService.resetPassword(id, request.getPassword());
        return Result.success();
    }
} 